<script setup lang="ts">
    import { ref, onMounted, onBeforeUnmount, reactive, watch, nextTick } from 'vue';
    import Breadcrumb from '../../components/Breadcrumb.vue';
    import {useRouter, useRoute} from 'vue-router'
    import useClass from '../../hooks/useClass';
    import { show_error, show_loading, readClassData, stringToBoolean, deepCopy } from '../../utils/function';
    import { useAudioPlayer } from '../../hooks/useAudioPlayer';
    import useWord from '../../hooks/useWord';
    import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
    import WordMeaningDisplay from '../../components/WordMeaningDisplay.vue';
    import WordBox from '../../components/WordBox.vue';
    import { Headset, VideoPlay, VideoPause } from '@element-plus/icons-vue'
    import { useLanguagesStore } from '../../store/languages';
    import useAiChat from '../../hooks/useAiChat';
    import { useOptionStore } from '../../store/option';
    import { storeToRefs } from 'pinia';
    import AIDialogs from '../../components/AIDialogs.vue';

    const loadingObj = show_loading("正在获取数据……");
    const router = useRouter();
    const route = useRoute();
    const languagesStore = useLanguagesStore();
    const classId = ref(route.params.id);
    const {getClassFullInfoByID, editTranslationById, deleteClassFileIgnore} = useClass();
    const {getWordsByClassId, updateWordById, getWordBase64ByWord} = useWord();
    const {aiTranslation} = useAiChat();
    const optionStore = useOptionStore();
    const {option} = storeToRefs(optionStore);
    const aiDialogsRef = ref(null);

    let classInfo = reactive({
        translation: ""
    }),
    audioData = ref([]),
    jsonData = [],
    wordArray = ref([]),
    sentenceArray = ref([]);
    // 译文的数组，不需要是ref，不在界面展示
    let translationArray = [];

    // 分句的正则
    const punctuationReg = /[\.\?\!\n。？！]/;
    // const punctuationReg = /[，。？！【】（）《》“”；：\.\,\[\]\<\>\"\'「」]/;
    const sentenceDrawer = ref(false);
    const aiTranslationLoading = ref(false);
    const semiAutomaticAITranslationLoading = ref(false);

    const contentArray = ref([]);
    const tabsName = ref("mainText");
    const leftClickRule = ref("play");
    // 用于引用 WordMeaningDisplay 组件实例
    const wordMeaningDisplayRef = ref(null);
    // 控制组件的显示状态
    const isDisplayingWordMeaning = ref(false);
    const currentWordData = reactive({
        word: '未知单词',
        oartOfSpeech: '未知',
        pronunciation: '',
        interpretation: '无释义',
        other: '',
        spell: false
    });
    // 当前对单词操作的下标
    const nowWordOperateIndex = ref(-1);
    // 单词编辑弹窗
    const dialogWordEditVisible = ref(false);
    const dialogTranslationEditVisible = ref(false);
    const wordBoxBaseObject = {
        id: 0,
        inlineId: 0,
        word: "",
        oartOfSpeech: "noun",
        pronunciation: "",
        interpretation: "",
        other: "",
        applicable: 1,
        spell: true,
        startIndex: "",
        isSeparation: false,
        highlight: false
    };
    const wordEditData = reactive({
        ...wordBoxBaseObject
    });

    // 监听单词操作
    watch(nowWordOperateIndex, (newValue, oldValue)=>{
        if(newValue < 0 || newValue >= contentArray.value.length){
            return;
        }

        if(leftClickRule.value != "read"){
            const item = contentArray.value[newValue];
            seek(item.startTime);
        }
        
        const wordItem = wordArray.value[newValue];
        switch(leftClickRule.value){
            case "play":
                playWord(wordItem.content);
                break;
            case "see":
                openMeaningDisplay(wordItem.id);
                break;
            case "edit":
                editWord(wordItem);
                break;
            case "read":
                readSentence(newValue);
                break;
        }
    });

    getClassFullInfoByID(classId.value).then((result)=>{
        if(result.rows.length == 0 || result.rows[0].isFinish == 0){
            router.back();
            loadingObj.close();
            return;
        }

        if(!result.rows[0].translation){
            // 译文不能为null或undefined
            result.rows[0].translation = "";
        }
        Object.assign(classInfo, result.rows[0])
        translationArray = classInfo.translation.split("\n");
        return readClassData(classInfo);
    }).then((result)=>{
        audioData.value = result.audioData;
        jsonData = result.jsonData;

        return getWordsByClassId(classId.value);
        
        
    }).then((result)=>{
        wordArray.value = result.rows;
        return languagesStore.setLastViewId(classInfo.languageId, classId.value);
    }).then(()=>{
        contentArray.value = formatHTMLByArray(classInfo.content);
    }).catch((error)=>{
        show_error(error);
    }).finally(()=>{
        loadingObj.close();
    })

    const {
        audioRef,
        audioSrc,
        playSegmentDirectly,
        currentAudioTime,
        playAudio,
        pauseAudio,
        seek
    } = useAudioPlayer({
        audioDataRef: audioData
    });

    const audioWordRef = ref(null);

    // 监听2个音频播放器
    watch([audioRef, audioWordRef, option.value], (newValue, oldValue)=>{
        setAudioPlaybackRate(option.value.playSpeed, 'audio');
    }, { immediate: true })

    const isSpanClick = ref(false);
    const pClick = (index)=>{
        if(!isSpanClick.value){
            isSpanClick.value = true;
            // 使用 watch 如果点击的单词相同，不会触发，所以先设置成别的值
            nowWordOperateIndex.value = -1;
            nextTick(()=>{
                nowWordOperateIndex.value = index;
                isSpanClick.value = false;
            })
        }
    }

    const playWord = (word) => {
        getWordBase64ByWord(word, classInfo.languageId, classId.value).then((result)=>{
            // 停止播放音频
            pauseAudio();
            if(audioWordRef.value){
                audioWordRef.value.src = "data:audio/mp3;base64," + result;
                setAudioPlaybackRate(option.value.playSpeed, "word");
                audioWordRef.value.play();
            }else{
                throw Error("未找到音频播放器");
            }
        }).catch((error)=>{
            show_error(error, "播放音频失败")
        })
    }

    const handleDisplayClose = () => {
        isDisplayingWordMeaning.value = false;
    };

    function setAudioPlaybackRate(playbackRate, ref = 'all'){
        if(audioRef.value && ref != 'word'){
            audioRef.value.playbackRate = playbackRate;
        }

        if(audioWordRef.value && ref != 'audio'){
            audioWordRef.value.playbackRate = playbackRate;
        }
    }

    function readSentence(index){
        // 确保 index 在有效范围内
        index = Math.max(0, Math.min(index, contentArray.value.length - 1));

        let foundStartTime = contentArray.value[0].startTime; // 默认值：数组第一个对象的 startTime
        let foundEndTime = contentArray.value[contentArray.value.length - 1].endTime; // 默认值：数组最后一个对象的 endTime

        // --- 向前查找 startTime (从 index - 1 开始) ---
        // 目标：找到第一个符合正则的项 A，然后取 A 后面一项的 startTime
        for (let i = index - 1; i >= 0; i--) {
            const currentItem = contentArray.value[i];
            if (currentItem.child && currentItem.child.length > 0) {
                for (let j = 0; j < currentItem.child.length; j++) {
                    if (punctuationReg.test(currentItem.child[j].content)) {
                        // 找到了符合正则的项，现在我们取它的下一项的 startTime
                        // 检查 i + 1 是否还在数组范围内
                        if (i + 1 < contentArray.value.length) {
                            foundStartTime = contentArray.value[i + 1].startTime;
                        } else {
                            // 如果 i 已经是数组最后一项，那么 i + 1 就不存在了，
                            // 这种情况下，默认值 (contentArray.value[0].startTime) 可能是合适的
                        }
                        i = -1; // 强制退出循环，因为已经找到目标
                        break;
                    }
                }
            }
        }

        // --- 向后查找 endTime (从 index 开始) ---
        for (let i = index; i < contentArray.value.length; i++) {
            const currentItem = contentArray.value[i];
            if (currentItem.child && currentItem.child.length > 0) {
                for (let j = 0; j < currentItem.child.length; j++) {
                    if (punctuationReg.test(currentItem.child[j].content)) {
                        // 找到第一个符合的，就用它的 endTime
                        foundEndTime = currentItem.child[j].endTime;
                        i = contentArray.value.length; // 强制退出循环
                        break;
                    }
                }
            }
        }

        playSegmentDirectly(foundStartTime, foundEndTime);
    }

    function editWord(item){
        Object.assign(wordEditData, item, {
            word: item.content,
            spell: stringToBoolean(item.spell),
            applicable: parseInt(item.applicable)
        });
        dialogWordEditVisible.value = true;
    }

    const handleEditWord = ()=>{
        updateWordById(wordEditData.id, deepCopy(wordEditData), wordEditData.sort).then(()=>{
            const index = wordArray.value.findIndex(item => item.id == wordEditData.id);
            if(index == -1){
                ElMessage.warning("单词不存在");
                return;
            }
            Object.assign(wordArray.value[index], {
                oartOfSpeech: wordEditData.oartOfSpeech,
                pronunciation: wordEditData.pronunciation,
                interpretation: wordEditData.interpretation,
                other: wordEditData.other,
                spell: wordEditData.spell ? "true" : "false",
                applicable: String(wordEditData.applicable)
            });
            ElMessage.success("修改成功");
            dialogWordEditVisible.value = false;
        }).catch((error)=>{
            show_error(error, "单词修改失败");
        });
    };

    const handleEditTranslation = ()=>{
        editTranslationById(classId.value, classInfo.translation).then(()=>{
            ElMessage.success("修改成功");
            dialogTranslationEditVisible.value = false;
            // 句子数组赋值
            translationArray = classInfo.translation.split("\n");
            addTransitionForSentence();
        }).catch((error)=>{
            show_error(error, "译文修改失败");
        })
    }

    const editWords = ()=>{
        router.push({
            path: "/word/operate/edit/" + classId.value
        });
    }

    const handleDeleteClass = ()=>{
        ElMessageBox.confirm(
            '确定要删除课文吗？',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(()=>{
            return deleteClassFileIgnore(classInfo.filePath, classInfo.audioFileName, classInfo.audioSrtJsonName , classId.value);
        }).then(()=>{
            ElMessage.success("删除成功");
            router.replace({
                path: "/class/list/" + classInfo.languageId
            })
        }).catch((error)=>{
            if(error != "cancel"){
                show_error(error);
            }
        })
    }

    // const handleAITranslation = ()=> {
    //     aiTranslationLoading.value = true;
    //     aiTranslation(classInfo.content).then((result)=>{
    //         classInfo.translation = result;
    //     }).catch((error)=>{
    //         show_error(error, "AI翻译失败");
    //     }).finally(()=>{
    //         aiTranslationLoading.value = false;
    //     })
    // }

    const playSentence = (index)=>{
        const item = sentenceArray.value[index];
        // console.log(sentenceArray.value[index])
        playSegmentDirectly(item.startTime, item.endTime)
    }

    function openDialog(){
        // 对话框打开停止监听
        window.removeEventListener('keydown', handleKeyDown);
    }

    function closeDialog(){
        // 对话框关闭重新监听
        window.addEventListener('keydown', handleKeyDown);
    }

    const handleAITranslation = async (auto)=>{
        if(!auto){
            // 半自动，查看ref是否准备完全
            if (aiDialogsRef.value) {
                // 等待用户反应
                const showResult = await aiDialogsRef.value.show();
                if (!showResult) {
                    return;
                }
            }else{
                show_error("无法打开AI对话框", "系统错误");
                return;
            }
        }

        const tempArray  =sentenceArray.value.map((n, i) => (i + 1) + ". " + n.content.replace(/\n/g, "")).filter(n => n.trim() != "");
        const text = tempArray.join("\n");

        aiTranslationLoading.value = true;
        semiAutomaticAITranslationLoading.value = true;
        const loadingObj = show_loading("正在进行AI翻译");
        let result;
        try {           
            if(auto){
                // 自动翻译
                result = await aiTranslation(text);
            }else{
                result = await aiDialogsRef.value.run(text, 1,  1);
            }
            console.log("AI翻译结果：", result);
        } catch (error) {
            show_error(error, "ai翻译中断");
        } finally {
            loadingObj.close();
            aiTranslationLoading.value = false;
            semiAutomaticAITranslationLoading.value = false;
        }

        const aiArray = result.split("\n");
        if(aiArray.length != tempArray.length){
            ElMessage.warning("AI翻译的行数与原文行数不匹配，无法进行句子对照");
        }

        const rule = /^\d+\. ?/;
        const resultText = aiArray.map((n) => {
            if(rule.test(n)){
                return n.replace(rule, "");
            }
            return n;
        }).join("\n");
        
        classInfo.translation = resultText;
    }

    function openMeaningDisplay(id){
        const index = wordArray.value.findIndex(item => item.id == id);
        if(index == -1){
            ElMessage.warning("单词不存在");
            return;
        }
        const item = wordArray.value[index];

        Object.assign(currentWordData, {
            word: item.content,
            oartOfSpeech: item.oartOfSpeech,
            pronunciation: item.pronunciation,
            interpretation: item.interpretation,
            other: item.other,
            spell: stringToBoolean(item.spell)
        });
        
        if (wordMeaningDisplayRef.value) {
            wordMeaningDisplayRef.value.show(currentWordData);
        }
    };
    
    function formatHTMLByArray(msg){
        let startIndex = 0;
        const childArray = [];
        // 分句需要的变量
        let sentenceMsg = "", sentenceStartTime = 0, sentenceEndTime = 0;
        
        // 先循环 jsonData 数组，用来创建内层的b标签
        for(let i = 0; i < jsonData.length; i++){
            const item = jsonData[i];
            const searchText = item.Metadata[0].Data.text.Text;
            const jsonTextLength = item.Metadata[0].Data.text.Length;
            let textLength = 0;
            startIndex = msg.indexOf(searchText, startIndex);

            if(startIndex != -1){
                // 找到了字符串，判断是否是最后一项
                if(i != jsonData.length - 1){
                    // 不是最后一项，读取下一项文字的第一个字符，因为要考虑空格和标点符号，不能单纯读取长度
                    const nextItem = jsonData[i + 1];
                    const nextSearchText = nextItem.Metadata[0].Data.text.Text;
                    const nextStartIndex = msg.indexOf(nextSearchText, startIndex + jsonTextLength);

                    if(nextStartIndex != -1){
                        textLength = nextStartIndex - startIndex;
                    }else{
                        textLength = jsonTextLength;
                    }
                }else{
                    // 如果是最后一项
                    textLength = msg.length - startIndex;
                }

                const endIndex = startIndex + textLength;
                const subString = msg.substring(startIndex, endIndex);

                const startTime = item.Metadata[0].Data.Offset / 10000000;
                const duration = item.Metadata[0].Data.Duration / 10000000;
                const endTime = startTime + duration;
                childArray.push({
                    content: subString,
                    startTime,
                    endTime
                })

                if(sentenceMsg == ""){
                    sentenceStartTime = startTime;
                }
                sentenceMsg += subString;
                sentenceEndTime = endTime;
                // 判断subString是否包含标点符号，用来分句
                if(punctuationReg.test(subString)){
                    sentenceArray.value.push({
                        content: sentenceMsg,
                        startTime: sentenceStartTime,
                        endTime: sentenceEndTime
                    });
                    sentenceMsg = "";
                }else if(i == jsonData.length - 1){
                    sentenceArray.value.push({
                        content: sentenceMsg,
                        startTime: sentenceStartTime,
                        endTime: sentenceEndTime
                    });
                }
            }
        }

        if(childArray.length != jsonData.length){
            show_error("分词出错，请复制必要数据联系作者。<br>数据："+JSON.stringify(classInfo), "系统错误");
            return;
        }

        // 分词分句成功，添加翻译
        addTransitionForSentence();

        const spanArray = [];
        // 循环 wordArray 创建 span
        for(let i = 0; i < wordArray.value.length; i++){
            const item = wordArray.value[i];
            let child = [], startTime = childArray[item.startIndex].startTime, endTime = 0;
            let conditionNumber = 0;
            let isBr = false;

            if(i != wordArray.value.length - 1){
                const nextItem = wordArray.value[i + 1];
                conditionNumber = nextItem.startIndex;
            }else{
                conditionNumber = childArray.length;
            }

            for(let j = item.startIndex; j < conditionNumber; j++){
                const bItem = childArray[j];
                if(/\n/.test(bItem.content)){
                    isBr = true;
                }
                child.push(bItem);
                endTime = bItem.endTime;
            }

            spanArray.push({
                child,
                startTime,
                endTime,
                isBr
            })
        }
        console.log(spanArray)
        return spanArray;
    }

    // 给句子数组添加翻译   
    function addTransitionForSentence(){
        if(sentenceArray.value.length == translationArray.length){
            sentenceArray.value.forEach((item, index) => {
                item.transition = translationArray[index];
            });
        }
    }

    // --- 键盘事件监听 ---
    const handleKeyDown = (event) => {
        if(!event.repeat){
            // 只有在不重复时才触发
            if(event.code == "Space"){
                handlePlayAudio();
                event.preventDefault();
            }else if(event.code == "KeyT"){
                changeTab();
                event.preventDefault();
            }else if(event.code == "KeyP"){
                changeLeftClickRule("play");
            }else if(event.code == "KeyR"){
                changeLeftClickRule("read");
            }else if(event.code == "KeyE"){
                changeLeftClickRule("edit");
            }else if(event.code == "KeyS"){
                changeLeftClickRule("see");
            }else if(event.code == "KeyC"){
                closeMeaningDisplay();
            }else if(event.code == "ArrowUp"){
                if(nowWordOperateIndex.value < contentArray.value.length - 1){
                    nowWordOperateIndex.value++;
                }
                event.preventDefault();
            }else if(event.code == "ArrowDown"){
                if(nowWordOperateIndex.value > 0){
                    nowWordOperateIndex.value--;
                }
                event.preventDefault();
            }else if(event.code == "KeyA"){
                sentenceDrawer.value = !sentenceDrawer.value;
                event.preventDefault();
            }
        }
    };

    function handlePlayAudio(){
        if(audioRef.value.paused){
            playAudio();
        }else{
            pauseAudio();
        }
    }

    function changeTab(){
        if(tabsName.value == "mainText"){
            tabsName.value = "translation";
            showNotification("译文");
        }else{
            tabsName.value = "mainText";
            showNotification("正文");
        }
    }

    function changeLeftClickRule(rule){
        if(leftClickRule.value == rule){
            return;
        }
        leftClickRule.value = rule;
        if(rule == "play"){
            showNotification("左键点击：播放音频");
        }else if(rule == "read"){
            showNotification("左键点击：播放句子");
        }else if(rule == "edit"){
            showNotification("左键点击：编辑单词");
        }else if(rule == "see"){
            showNotification("左键点击：查看释义");
        }
    }

    function closeMeaningDisplay(){
        if (wordMeaningDisplayRef.value) {
            wordMeaningDisplayRef.value.hide();
        }
    }

    function showNotification(message){
        ElNotification({
            title: '通知',
            message,
            type: 'info',
            duration: 2000
        })
    }

    onMounted(() => {
        window.addEventListener('keydown', handleKeyDown);
    });

    onBeforeUnmount(() => {
        window.removeEventListener('keydown', handleKeyDown);
    });
</script>

<template>
    <div class="class-show-div">
        <div class="class-show-header">
            <Breadcrumb :text="classInfo == null ? '' : classInfo.title"/>
        </div>
        <div class="class-show-body">
            <div class="class-show-body-tool-box">
                <div class="tool-item">
                    <p>点击规则：</p>
                    <el-radio-group v-model="leftClickRule">
                        <el-radio-button label="播放单词" value="play" />
                        <el-radio-button label="播放句子" value="read" />
                        <el-radio-button label="查看释义" value="see" />
                        <el-radio-button label="编辑单词" value="edit" />
                    </el-radio-group>
                </div>
                <div class="tool-item">
                    <p>全篇工具：</p>
                    <el-button @click="editWords">编辑单词</el-button>
                    <el-button @click="dialogTranslationEditVisible = true">编辑译文</el-button>
                    <el-button type="success" @click="sentenceDrawer = true">句子列表</el-button>
                    <el-button type="danger" @click="handleDeleteClass">删除课文</el-button>
                </div>
            </div>
            <div class="clss-show-body-main-content">
                <el-tabs
                    v-model="tabsName"
                    type="card"
                >
                    <el-tab-pane label="正文" name="mainText">
                        <template v-for="item,index in contentArray">
                            <p @click="pClick(index)" :class="['word-p', `pos-${wordArray[index].oartOfSpeech}`, {'hide-pos': !option.showOartOfSpeech}]">
                                <span 
                                    v-for="bItem in item.child" 
                                    :class="{'active': currentAudioTime > bItem.startTime && currentAudioTime < bItem.endTime}"
                                >
                                    {{ bItem.content.replace(/ /g, '&nbsp;') }}
                                </span>
                            </p>
                            <br v-if="item.isBr" />
                        </template>
                    </el-tab-pane>

                    <el-tab-pane label="译文" name="translation" v-html="classInfo.translation.replace(/\n/g, '<br>')">
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>

        <!-- 单词详情 -->
        <WordMeaningDisplay
        ref="wordMeaningDisplayRef" 
        v-model="isDisplayingWordMeaning"
        :data="currentWordData"
        @close="handleDisplayClose" />

        <!-- 单词编辑 -->
        <el-dialog v-model="dialogWordEditVisible" title="编辑单词" width="1100" @close="closeDialog" @open="openDialog">
            <WordBox v-model="wordEditData" :showTool="false"/>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogWordEditVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleEditWord">确认</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 译文编辑 -->
        <el-dialog v-model="dialogTranslationEditVisible" title="编辑译文" width="1100" @close="closeDialog" @open="openDialog">
            <el-input
                v-model="classInfo.translation"
                :rows="20"
                type="textarea"
                placeholder="推荐使用AI翻译，手动输入无法进行句子匹配"
            />
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogTranslationEditVisible = false">取消</el-button>
                    <el-button type="success" @click="handleAITranslation(true)" :loading="aiTranslationLoading">全自动AI翻译</el-button>
                    <el-button type="info" @click="handleAITranslation(false)" :loading="semiAutomaticAITranslationLoading">半自动AI翻译（无需API密钥）</el-button>
                    <el-button type="primary" @click="handleEditTranslation">确认</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 句子朗读 -->
        <el-drawer
            v-model="sentenceDrawer"
            title="句子朗读"
            :direction="'rtl'"
            size="400px"
        >
            <div class="sentence-container">
                <div class="sentence-item" v-for="(item, index) in sentenceArray" :key="index">
                    <div class="sentence-content">
                        <div class="sentence-text">
                            <p class="original-text">{{ item.content.replace(punctuationReg, '') }}</p>
                            <div class="translation">
                                <span class="translation-text">{{ item.transition || '无，点编辑译文添加' }}</span>
                            </div>
                        </div>
                        <div class="sentence-actions">
                            <el-button :icon="VideoPlay" circle @click="playSentence(index)" :type="''" />
                        </div>
                    </div>
                    <div class="divider"></div>
                </div>

                <div v-if="sentenceArray.length === 0" class="empty-state">
                    <el-empty description="暂无句子数据" />
                </div>
            </div>
        </el-drawer>

        <!-- 音频播放 -->
        <audio class="playAudio" ref="audioRef" controls></audio>
        <!-- 单词播放 -->
        <audio ref="audioWordRef"></audio>

        <!-- AI对话框 -->
        <AIDialogs ref="aiDialogsRef" :type="'translation'"></AIDialogs>
    </div>
</template>

<style scoped>
    .class-show-div{
        display: flex;
        flex-direction: column;
    }
    .class-show-body{
        flex-grow: 1;
        overflow-y: auto;
        display: flex;
        flex-direction: column;
    }
    .clss-show-body-main-content{
        flex-grow: 1;
        overflow-y: auto;
    }
    .clss-show-body-main-content span.active{
        color: red;
    }
    .playAudio{
        flex-shrink: 0;
        width: 100%;
    }
    .tool-item{
        display: flex;
        margin-bottom: 15px;
    }

    .tool-item p{
        margin-right: 10px;
    }
    .class-show-body-tool-box{
        margin-bottom: 25px;
    }

    .el-tabs--top{
        height: 100%;
    }

    .sentence-item{
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        border: 1px solid #ccc;
        padding: 5px;
    }

    .word-p.hide-pos::after{
        display: none;
    }

    .word-p{
        cursor: pointer;
        user-select: none;
        position: relative; /* 相对定位，以便 ::after 绝对定位 */
        display: inline-block; /* 确保能应用宽度和定位 */
        padding-bottom: 5px; /* 为下划线留出空间 */
    }

    .word-p::after {
        content: ''; /* 伪元素必须有 content */
        position: absolute;
        left: 0;
        bottom: 0; /* 定位在单词下方 */
        width: 90%; /* 留一点空隙 */
        height: 3px; /* 下划线高度 */
        border-radius: 2px; /* 稍微圆角 */
        transition: background-color 0.3s ease; /* 颜色切换动画 */
    }

    /* 根据词性动态绑定的类名和颜色 */
    .pos-noun::after {
        background-color: #67C23A; /* 名词 */
    }

    .pos-numeral::after {
        background-color: #E6A23C; /* 数词 */
    }

    .pos-measure_word::after {
        background-color: #F56C6C; /* 量词 */
    }

    .pos-verb::after {
        background-color: #409EFF; /* 动词 */
    }

    .pos-adjective::after {
        background-color: #909399; /* 形容词 */
    }

    .pos-distinguishing_word::after {
        background-color: #B3E19D; /* 区别词 */
    }

    .pos-adverb::after {
        background-color: #606266; /* 副词 */
    }

    .pos-conjunction::after {
        background-color: #D3DCE6; /* 连词 */
    }

    .pos-preposition::after {
        background-color: #EBEEF5; /* 介词 */
    }

    .pos-auxiliary::after {
        background-color: #F2F6FC; /* 助词 */
    }

    .pos-modal_particle::after {
        background-color: #FDE2E2; /* 语气词 */
    }

    .pos-phrase::after {
        background-color: #9FE6B8; /* 短语 */
    }

    .pos-sentence_fragment::after {
        background-color: #BFE8F6; /* 短句 */
    }

    .pos-pronoun::after {
        background-color: #F7B3D0; /* 代词 */
    }

    .pos-interjection::after {
        background-color: #FFD700; /* 叹词 */
    }

    .pos-onomatopoeia::after {
        background-color: #ADD8E6; /* 拟声词 */
    }

    .pos-morpheme::after {
        background-color: #DDA0DD; /* 语素 */
    }

    .pos-other::after {
        background-color: #D9D9D9; /* 其他 */
    }

    /* 句子朗读 */
    .sentence-container {
        padding: 0 20px;
        height: 100%;
        overflow-y: auto;
    }

    .sentence-item {
        padding: 10px;
        transition: all 0.3s ease;
    }

    .sentence-item.active {
        background: linear-gradient(135deg, #f0f7ff 0%, #e1eeff 100%);
        border-radius: 8px;
        padding: 16px;
    }

    .sentence-content {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        width: 100%;
    }

    .sentence-text {
        flex: 1;
        min-width: 0;
    }

    .original-text {
        font-size: 16px;
        line-height: 1.6;
        color: #2c3e50;
        margin-bottom: 8px;
        font-weight: 500;
    }

    .translation {
        display: flex;
        align-items: flex-start;
        gap: 8px;
        padding: 10px;
        background: #f8f9fa;
        border-radius: 6px;
        border-left: 3px solid #409eff;
    }

    .translation-text {
        font-size: 14px;
        color: #555;
        line-height: 1.5;
        flex: 1;
    }

    .translation-text:empty::before {
        content: "无";
        color: #999;
        font-style: italic;
    }

    .sentence-actions {
        flex-shrink: 0;
    }

    .divider {
        height: 1px;
        background: linear-gradient(90deg, transparent 0%, #e0e0e0 50%, transparent 100%);
        margin: 8px 0;
    }

    .empty-state {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 200px;
    }

    /* 滚动条样式 */
    .sentence-container::-webkit-scrollbar {
        width: 6px;
    }

    .sentence-container::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }

    .sentence-container::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;
    }

    .sentence-container::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
        .sentence-container {
            padding: 0 16px;
        }

        .sentence-content {
            flex-direction: column;
            align-items: stretch;
            gap: 12px;
        }

        .sentence-actions {
            align-self: flex-end;
        }

        .sentence-item.active {
            margin: 0 -12px;
            padding: 12px;
        }
    }

</style>

<style>
    .el-tabs__content{
        overflow-y: auto !important;
        padding-bottom: 10px;
    }
</style>